//
//  MyVideoViewController.m
//  miaopai
//
//  Created by Crow Zhang on 15/11/23.
//  Copyright © 2015年 Crow Zhang. All rights reserved.
//

#import "MyVideoViewController.h"
#import "CoreData.h"
#import "MyVideo.h"
#import "MyselfAVPlayer.h"

@interface MyVideoViewController ()<UITableViewDataSource, UITableViewDelegate>

@property(nonatomic, retain)CoreData *coreData;

@property(nonatomic, retain)NSMutableArray *videoArray;

@property(nonatomic, retain)UITableView *tableView;

@property(nonatomic, retain)MyselfAVPlayer *avplayer;

@property(nonatomic, retain)UIVisualEffectView *effectView;

@property(nonatomic, retain)UIButton *closeButton;

@end

@implementation MyVideoViewController

- (void)dealloc
{
    [_coreData release];
    [_videoArray release];
    [_tableView release];
    [_avplayer release];
    [_effectView release];
    [_closeButton release];
    [super dealloc];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"我的视频";
    
    [self.navigationController.navigationBar setTintColor:[UIColor blackColor]];
    
    self.coreData = [CoreData shareManagerWithFile:@"joke"];
    
    self.tableView = [[UITableView alloc] initWithFrame:self.view.frame style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"MyVideoTableViewCell"];
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:self.tableView];
    
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"MyVideo" inManagedObjectContext:_coreData.managedObjectContext];
    [fetchRequest setEntity:entity];
    // Specify criteria for filtering which objects to fetch
//    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"<#format string#>", <#arguments#>];
//    [fetchRequest setPredicate:predicate];
    // Specify how the fetched objects should be sorted
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];
    
    NSError *error = nil;
    NSArray *fetchedObjects = [_coreData.managedObjectContext executeFetchRequest:fetchRequest error:&error];
    if (fetchedObjects == nil) {
        NSLog(@"%@", error);
    }else
    {
        self.videoArray = [NSMutableArray arrayWithArray:fetchedObjects];
        [self.tableView reloadData];
        if (self.videoArray.count == 0) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 75, kWidth, 20)];
            label.text = @"暂时没有视频哦， 赶紧去录一段～";
            label.textColor = [UIColor colorWithRed:0.5709 green:0.5709 blue:0.5709 alpha:1.0];
            label.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:label];
            [label release];
        }
    }
    
    self.effectView = [[UIVisualEffectView alloc] initWithEffect:[UIBlurEffect effectWithStyle:UIBlurEffectStyleDark]];
    self.effectView.frame = self.view.frame;
    self.effectView.userInteractionEnabled = YES;
    self.effectView.alpha = 0;
    
    self.avplayer = [MyselfAVPlayer myselfAVPlayerShareHandle];
    self.avplayer.frame = CGRectMake(0, kHeight + kWidth, kWidth, kWidth);
    self.avplayer.alpha = 0;
    self.avplayer.center = self.view.center;
    [self.effectView addSubview:self.avplayer];
    
    self.closeButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.closeButton.frame = CGRectMake(kWidth / 2 - 20, kHeight + 50, 40, 40);
    [self.closeButton setImage:[UIImage imageNamed:@"iconfont-guanbi-3"] forState:UIControlStateNormal];
    [self.closeButton addTarget:self action:@selector(close) forControlEvents:UIControlEventTouchUpInside];
    [self.effectView addSubview:self.closeButton];
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.videoArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 100;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MyVideoTableViewCell" forIndexPath:indexPath];
    MyVideo *video = [self.videoArray objectAtIndex:indexPath.row];
    [cell.imageView setImage:[UIImage imageWithContentsOfFile:video.picURL]];
    cell.textLabel.text = video.time;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MyVideo *video = [self.videoArray objectAtIndex:indexPath.row];
    self.avplayer.fileURL = video.videoURL;
    [self.view addSubview:self.effectView];
    [UIView animateWithDuration:0.5 animations:^{
        self.effectView.alpha = 1;
        self.avplayer.alpha = 1;
        self.closeButton.frame = CGRectMake(kWidth / 2 - 20, kHeight - 50, 40, 40);
        self.navigationController.navigationBarHidden = YES;
    }];
    
    
    [self.avplayer palyAVPlayer];
    
}

#pragma mark 是否能被编辑
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
    return YES;
}

#pragma mark 编辑类型
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

#pragma mark 删除的实现
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(editingStyle == UITableViewCellEditingStyleDelete)
    {
        MyVideo *video = [self.videoArray objectAtIndex:indexPath.row];
        [_coreData.managedObjectContext deleteObject:video];
        [_coreData saveContext];
        [self.videoArray removeObjectAtIndex:indexPath.row];
        [self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationMiddle];
        NSFileManager *manager = [NSFileManager defaultManager];
        [manager removeItemAtPath:video.videoURL error:nil];
        [manager removeItemAtPath:video.picURL error:nil];
        if (self.videoArray.count == 0) {
            UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 70, kWidth, 50)];
            label.text = @"暂时没有视频哦， 赶紧去录一段～";
            label.textColor = [UIColor grayColor];
            label.textAlignment = NSTextAlignmentCenter;
            [self.view addSubview:label];
            [label release];
        }
        
    }
}

- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return @"删除" ;
}

- (void)close
{
    [UIView animateWithDuration:0.5 animations:^{
        self.effectView.alpha = 0;
        self.avplayer.alpha = 0;
        self.closeButton.frame = CGRectMake(kWidth / 2 - 20, kHeight + 50, 40, 40);
        self.navigationController.navigationBarHidden = NO;
        [self.effectView removeFromSuperview];
    }];
    
}

- (void)viewWillAppear:(BOOL)animated
{
    
    [super viewWillAppear:YES];
    UIView * view = [self.tabBarController.view.subviews lastObject];
    [UIView animateWithDuration:0.5 animations:^{
        view.frame = CGRectMake(0, kHeight + 100, kWidth, 48);
    }];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
